import { json, error } from '@sveltejs/kit'; import { createAirtableServices } from '$lib/airtable'; import type { RequestHandler } from './$types'; const apiKey = process.env.VITE_AIRTABLE_API_KEY; const baseId = process.env.VITE_AIRTABLE_BASE_ID; if (!apiKey || !baseId) { throw new Error('Airtable API key and base ID must be configured'); } const airtable = createAirtableServices(apiKey, baseId); // GET /api/plants/[id] - Get a specific plant export const GET: RequestHandler = async ({ params }) => { try { const { id } = params; const record = await airtable.plants.getRecord(id); const plant = { id: record.id, ...record.fields, lastWatered: record.fields.lastWatered ? new Date(record.fields.lastWatered) : new Date(), nextWatering: record.fields.nextWatering ? new Date(record.fields.nextWatering) : new Date(), careInstructions: record.fields.careInstructions ? JSON.parse(record.fields.careInstructions) : [], growthStages: record.fields.growthStages ? JSON.parse(record.fields.growthStages) : [], additionalImages: record.fields.additionalImages ? JSON.parse(record.fields.additionalImages) : [] }; return json(plant); } catch (err) { console.error('Error fetching plant:', err); throw error(404, 'Plant not found'); } }; // PUT /api/plants/[id] - Update a plant export const PUT: RequestHandler = async ({ params, request }) => { try { const { id } = params; const plantData = await request.json(); // Convert Date objects to ISO strings for Airtable const fields = { ...plantData, lastWatered: plantData.lastWatered?.toISOString(), nextWatering: plantData.nextWatering?.toISOString(), careInstructions: plantData.careInstructions ? JSON.stringify(plantData.careInstructions) : null, growthStages: plantData.growthStages ? JSON.stringify(plantData.growthStages) : null, additionalImages: plantData.additionalImages ? JSON.stringify(plantData.additionalImages) : null }; const record = await airtable.plants.updateRecord(id, fields); // Convert back to our format const plant = { id: record.id, ...record.fields, lastWatered: record.fields.lastWatered ? new Date(record.fields.lastWatered) : new Date(), nextWatering: record.fields.nextWatering ? new Date(record.fields.nextWatering) : new Date(), careInstructions: record.fields.careInstructions ? JSON.parse(record.fields.careInstructions) : [], growthStages: record.fields.growthStages ? JSON.parse(record.fields.growthStages) : [], additionalImages: record.fields.additionalImages ? JSON.parse(record.fields.additionalImages) : [] }; return json(plant); } catch (err) { console.error('Error updating plant:', err); throw error(500, 'Failed to update plant'); } }; // DELETE /api/plants/[id] - Delete a plant export const DELETE: RequestHandler = async ({ params }) => { try { const { id } = params; await airtable.plants.deleteRecord(id); return json({ success: true }); } catch (err) { console.error('Error deleting plant:', err); throw error(500, 'Failed to delete plant'); } };